<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🎭 智能童话书 - ERNIE大模型驱动</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #ff6b6b;
            --secondary-color: #4ecdc4;
            --accent-color: #45b7d1;
            --warm-color: #ffa726;
            --success-color: #66bb6a;
            --gradient-bg: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --card-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }

        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background: var(--gradient-bg);
            min-height: 100vh;
            margin: 0;
            padding: 0;
        }

        .fairy-tale-container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: var(--card-shadow);
            margin: 20px;
            padding: 30px;
            backdrop-filter: blur(10px);
        }

        .header-section {
            text-align: center;
            margin-bottom: 40px;
            padding: 20px;
            background: linear-gradient(45deg, var(--primary-color), var(--secondary-color));
            border-radius: 15px;
            color: white;
        }

        .header-section h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .competition-badge {
            background: rgba(255,255,255,0.2);
            padding: 10px 20px;
            border-radius: 25px;
            display: inline-block;
            margin-top: 10px;
            font-weight: bold;
        }

        .control-panel {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 30px;
            border: 2px solid #e9ecef;
        }

        .story-display {
            background: linear-gradient(135deg, #fff5f5 0%, #f0f8ff 100%);
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            border: 2px solid var(--secondary-color);
            min-height: 300px;
            position: relative;
            overflow: hidden;
        }

        .story-content {
            position: relative;
            z-index: 1;
            font-size: 1.1rem;
            line-height: 1.8;
            color: #333;
        }

        .choices-section {
            background: #fff;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .choice-btn {
            background: linear-gradient(45deg, var(--accent-color), var(--secondary-color));
            border: none;
            color: white;
            padding: 15px 25px;
            border-radius: 25px;
            margin: 10px;
            font-size: 1rem;
            font-weight: bold;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }

        .choice-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.3);
            background: linear-gradient(45deg, var(--secondary-color), var(--accent-color));
        }

        .theme-selector {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .theme-card {
            background: linear-gradient(135deg, var(--warm-color), var(--primary-color));
            color: white;
            padding: 20px;
            border-radius: 15px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 3px solid transparent;
        }

        .theme-card:hover, .theme-card.selected {
            transform: scale(1.05);
            border-color: var(--success-color);
            box-shadow: 0 8px 25px rgba(0,0,0,0.2);
        }

        .character-input {
            background: #fff;
            border: 2px solid var(--secondary-color);
            border-radius: 10px;
            padding: 15px;
            font-size: 1.1rem;
            width: 100%;
            margin-bottom: 20px;
        }

        .generate-btn {
            background: linear-gradient(45deg, var(--success-color), var(--secondary-color));
            border: none;
            color: white;
            padding: 15px 40px;
            border-radius: 25px;
            font-size: 1.2rem;
            font-weight: bold;
            width: 100%;
            transition: all 0.3s ease;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }

        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }

        .loading.show {
            display: block;
        }

        .educational-panel {
            background: linear-gradient(135deg, #e8f5e8 0%, #f0f8ff 100%);
            border-radius: 15px;
            padding: 20px;
            margin-top: 20px;
            border: 2px solid var(--success-color);
        }

        .status-indicator {
            position: fixed;
            top: 20px;
            right: 20px;
            background: rgba(255,255,255,0.9);
            padding: 10px 15px;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            z-index: 1000;
        }

        .status-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 8px;
        }

        .status-online { background-color: var(--success-color); }
        .status-offline { background-color: #f44336; }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="fairy-tale-container">
            <!-- 状态指示器 -->
            <div class="status-indicator">
                <span class="status-dot status-offline" id="statusDot"></span>
                <span id="statusText">连接中...</span>
            </div>

            <!-- 头部区域 -->
            <div class="header-section">
                <h1><i class="fas fa-book-open"></i> 智能童话书</h1>
                <p class="mb-2">基于ERNIE-4.5-0.3B大模型 + 智源研究院数据</p>
                <div class="competition-badge">
                    🏆 GitCode&文心大模型&智源研究院AI应用开发大赛 - 赛道二
                </div>
            </div>

            <!-- 控制面板 -->
            <div class="control-panel">
                <h3><i class="fas fa-magic"></i> 创作设置</h3>
                
                <!-- 主题选择 -->
                <div class="mb-4">
                    <h5>选择故事主题：</h5>
                    <div class="theme-selector">
                        <div class="theme-card" data-theme="adventure">
                            <i class="fas fa-mountain fa-2x mb-2"></i>
                            <h6>奇幻冒险</h6>
                            <small>勇气与探索</small>
                        </div>
                        <div class="theme-card" data-theme="friendship">
                            <i class="fas fa-heart fa-2x mb-2"></i>
                            <h6>友谊故事</h6>
                            <small>友爱与分享</small>
                        </div>
                        <div class="theme-card" data-theme="learning">
                            <i class="fas fa-graduation-cap fa-2x mb-2"></i>
                            <h6>学习成长</h6>
                            <small>智慧与坚持</small>
                        </div>
                        <div class="theme-card" data-theme="nature">
                            <i class="fas fa-leaf fa-2x mb-2"></i>
                            <h6>自然探索</h6>
                            <small>环保与科学</small>
                        </div>
                    </div>
                </div>

                <!-- 角色设置 -->
                <div class="mb-4">
                    <h5>主角名字：</h5>
                    <input type="text" class="character-input" id="characterName" 
                           placeholder="给你的小主角起个名字吧（留空将随机生成）">
                </div>

                <!-- 教育重点 -->
                <div class="mb-4">
                    <h5>教育重点：</h5>
                    <select class="form-select character-input" id="educationalFocus">
                        <option value="">随机选择</option>
                        <option value="science">科学知识</option>
                        <option value="math">数学思维</option>
                        <option value="language">语言表达</option>
                        <option value="social">社会品德</option>
                    </select>
                </div>

                <!-- 生成按钮 -->
                <button class="generate-btn" id="generateBtn">
                    <i class="fas fa-sparkles"></i> 开始创作童话故事
                </button>

                <!-- 加载状态 -->
                <div class="loading" id="loadingDiv">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">生成中...</span>
                    </div>
                    <p class="mt-2">ERNIE大模型正在为您创作精彩的童话故事...</p>
                </div>
            </div>

            <!-- 故事显示区域 -->
            <div class="story-display" id="storyDisplay" style="display: none;">
                <h4 id="storyTitle"><i class="fas fa-book"></i> 童话故事</h4>
                <div class="story-content" id="storyContent">
                    故事将在这里显示...
                </div>
            </div>

            <!-- 选择分支区域 -->
            <div class="choices-section" id="choicesSection" style="display: none;">
                <h5><i class="fas fa-road"></i> 选择故事发展方向：</h5>
                <div id="choicesContainer">
                    <!-- 选择按钮将在这里动态生成 -->
                </div>
            </div>

            <!-- 教育价值展示 -->
            <div class="educational-panel" id="educationalPanel" style="display: none;">
                <h5><i class="fas fa-lightbulb"></i> 教育价值与学习建议</h5>
                <div id="educationalContent">
                    <!-- 教育内容将在这里显示 -->
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let selectedTheme = 'adventure';
        let currentStoryData = null;

        // 检查系统状态
        function checkSystemStatus() {
            fetch('/api/system_status')
                .then(response => response.json())
                .then(data => {
                    const statusDot = document.getElementById('statusDot');
                    const statusText = document.getElementById('statusText');
                    
                    if (data.status === 'running') {
                        statusDot.className = 'status-dot status-online';
                        statusText.textContent = `ERNIE模型${data.model_loaded ? '已加载' : '模拟模式'}`;
                    } else {
                        statusDot.className = 'status-dot status-offline';
                        statusText.textContent = '系统离线';
                    }
                })
                .catch(error => {
                    console.error('状态检查失败:', error);
                    document.getElementById('statusDot').className = 'status-dot status-offline';
                    document.getElementById('statusText').textContent = '连接失败';
                });
        }

        // 主题选择
        document.querySelectorAll('.theme-card').forEach(card => {
            card.addEventListener('click', function() {
                document.querySelectorAll('.theme-card').forEach(c => c.classList.remove('selected'));
                this.classList.add('selected');
                selectedTheme = this.dataset.theme;
            });
        });

        // 默认选择第一个主题
        document.querySelector('.theme-card').classList.add('selected');

        // 生成故事
        document.getElementById('generateBtn').addEventListener('click', function() {
            const characterName = document.getElementById('characterName').value.trim();
            const educationalFocus = document.getElementById('educationalFocus').value;
            
            // 显示加载状态
            document.getElementById('loadingDiv').classList.add('show');
            this.disabled = true;

            const requestData = {
                theme: selectedTheme,
                character_name: characterName,
                educational_focus: educationalFocus || null
            };

            fetch('/api/generate_story', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displayStory(data.data);
                } else {
                    alert('故事生成失败: ' + data.error);
                }
            })
            .catch(error => {
                console.error('请求失败:', error);
                alert('网络错误，请重试');
            })
            .finally(() => {
                document.getElementById('loadingDiv').classList.remove('show');
                document.getElementById('generateBtn').disabled = false;
            });
        });

        // 显示故事
        function displayStory(storyData) {
            currentStoryData = storyData;
            
            // 显示故事内容
            document.getElementById('storyTitle').innerHTML = 
                `<i class="fas fa-book"></i> ${storyData.theme} - ${storyData.character}的故事`;
            document.getElementById('storyContent').innerHTML = storyData.story;
            document.getElementById('storyDisplay').style.display = 'block';

            // 显示选择分支
            if (storyData.choices && storyData.choices.length > 0) {
                displayChoices(storyData.choices);
            }

            // 显示教育价值
            if (storyData.educational_value || storyData.learning_suggestions) {
                displayEducationalContent(storyData);
            }

            // 滚动到故事区域
            document.getElementById('storyDisplay').scrollIntoView({ behavior: 'smooth' });
        }

        // 显示选择分支
        function displayChoices(choices) {
            const container = document.getElementById('choicesContainer');
            container.innerHTML = '';

            choices.forEach(choice => {
                const button = document.createElement('button');
                button.className = 'choice-btn';
                button.innerHTML = `<i class="fas fa-arrow-right"></i> ${choice.text}`;
                button.onclick = () => continueStory(choice.id);
                container.appendChild(button);
            });

            document.getElementById('choicesSection').style.display = 'block';
        }

        // 继续故事
        function continueStory(choiceId) {
            const requestData = {
                choice_id: choiceId,
                current_story: currentStoryData.story,
                theme: selectedTheme,
                character: currentStoryData.character
            };

            fetch('/api/continue_story', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 添加续写内容
                    const storyContent = document.getElementById('storyContent');
                    storyContent.innerHTML += data.data.continuation;
                    
                    // 更新选择分支
                    if (data.data.choices && data.data.choices.length > 0) {
                        displayChoices(data.data.choices);
                    } else {
                        document.getElementById('choicesSection').style.display = 'none';
                    }
                } else {
                    alert('故事续写失败: ' + data.error);
                }
            })
            .catch(error => {
                console.error('续写请求失败:', error);
                alert('网络错误，请重试');
            });
        }

        // 显示教育内容
        function displayEducationalContent(storyData) {
            let content = '<div class="row">';
            
            if (storyData.educational_value) {
                content += '<div class="col-md-6"><h6><i class="fas fa-star"></i> 教育价值</h6><ul>';
                storyData.educational_value.forEach(value => {
                    content += `<li>${value}</li>`;
                });
                content += '</ul></div>';
            }

            if (storyData.learning_suggestions) {
                content += '<div class="col-md-6"><h6><i class="fas fa-lightbulb"></i> 学习建议</h6><ul>';
                storyData.learning_suggestions.forEach(suggestion => {
                    content += `<li>${suggestion}</li>`;
                });
                content += '</ul></div>';
            }

            if (storyData.knowledge_enhancement) {
                content += '<div class="col-12 mt-3"><h6><i class="fas fa-brain"></i> 知识拓展</h6>';
                const knowledge = storyData.knowledge_enhancement;
                if (knowledge.question && knowledge.answer) {
                    content += `<p><strong>Q: ${knowledge.question}</strong></p>`;
                    content += `<p>A: ${knowledge.answer}</p>`;
                } else if (knowledge.element && knowledge.description) {
                    content += `<p><strong>${knowledge.element}:</strong> ${knowledge.description}</p>`;
                } else if (knowledge.skill && knowledge.tip) {
                    content += `<p><strong>${knowledge.skill}:</strong> ${knowledge.tip}</p>`;
                }
                content += '</div>';
            }

            content += '</div>';
            
            document.getElementById('educationalContent').innerHTML = content;
            document.getElementById('educationalPanel').style.display = 'block';
        }

        // 页面加载完成后检查状态
        document.addEventListener('DOMContentLoaded', function() {
            checkSystemStatus();
            // 每30秒检查一次状态
            setInterval(checkSystemStatus, 30000);
        });
    </script>
</body>
</html>